<template>
    <el-row style="margin-top: 15px;">
        <el-col :span="12">
            <el-image src="/src/assets/ad.png" />
        </el-col>
        <el-col :span="12">
            <el-form class="loginForm">
                <h1>用户注册</h1>
                <el-form-item>
                    <el-input prefix-icon="User" placeholder="请输入用户名" v-model="registerInfoDTO.name"/>
                </el-form-item>
                <el-form-item>
                    <el-input type="password" prefix-icon="Key" placeholder="请输入密码" v-model="registerInfoDTO.password"/>
                </el-form-item>
                <el-form-item>
                    <el-input prefix-icon="Key" placeholder="请输入手机号" v-model="registerInfoDTO.phone"/>
                </el-form-item>
                <el-form-item>
                    <el-input  prefix-icon="Key" placeholder="请输入邮箱" v-model="registerInfoDTO.email"/>
                </el-form-item>
                <el-form-item>
                    <el-input style="width: 175px; margin-right: 5px;" prefix-icon="Picture" placeholder="请输入验证码" v-model="registerInfoDTO.captcha" />
                    <img width="160px" :src="captcha" @click="loadCaptcha" alt="验证码"/>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" class="loginBtn" @click="register">登录</el-button>
                </el-form-item>
            </el-form>
        </el-col>
    </el-row>
</template>

<script setup>
    import userApi from "@/api/userApi.js";
    import {ref} from "vue";
    import {ElMessage} from "element-plus";
    import {useRouter} from "vue-router";
    import {useTokenStore} from "@/stores/token.js";
    import {useUserStore} from "@/stores/user.js";
    import captchaApi from "@/api/captcha.js";

    const tokenStore = useTokenStore();
    const userStore = useUserStore();
    const router = useRouter();
    //保存验证码
    const imageBase64Data = ref(null);
    //用户注册信息
    //定义数据模型
    const registerInfoDTO = ref({
        name: '',
        password: '',
        captcha: '',
        uuid: ''
    })

    //获取验证码
    const captcha = ref('')
    function loadCaptcha() {
        captchaApi.captcha().then(result => {
            captcha.value = result.data.captcha
            registerInfoDTO.value.uuid = result.data.uuid
        })
    }

    loadCaptcha()

    //用户登录
    function register() {
        userApi.register(registerInfoDTO.value).then(result => {
            ElMessage.success(result.msg);
            //保存token
            tokenStore.updateToken(result.data);
            //跳转到前台首页
            router.push("/login");
        });
    }

</script>

<style scoped>
    .loginForm {
        width: 300px;
        margin: 25px 150px;
    }

    .loginForm h1 {
        text-align: center;
        margin-bottom: 20px;
    }

    .loginBtn {
        width: 100%;
    }
</style>